package blue.tools.commons;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * Created by sanwa.hb on 2017-01-11.
 */
public class Base64Util {

    private static final Logger logger = LoggerFactory.getLogger(Base64Util.class);


    public static String encodeBase64(String s) {

        try {
            return encodeBase64(s.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("encodeBase64 exception. s=" + s,e);
            return encodeBase64(s.getBytes());
        }
    }

    public static String encodeBase64(byte[] b) {

        byte[] b2 = Base64.encodeBase64(b);

        try {
            return new String(b2, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("encodeBase64 exception",e);
            return new String(b2);
        }
    }

    public static byte[] decodeBase64(String s) {

        if (StringUtils.isEmpty(s)) {
            return null;
        }

        byte[] b;

        try {
            b = s.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("decodeBase64 exception. s=" + s,e);
            b = s.getBytes();
        }

        if (Base64.isBase64(b)) {
            return Base64.decodeBase64(b);
        } else {
            return null;
        }
    }

    public static String decodeBase64ToString(String s) {
        return decodeBase64ToString(s, null);
    }

    public static String decodeBase64ToString(String s, String charset) {

        byte[] result = decodeBase64(s);

        if (result != null) {
            try {
                return new String(result,
                                  StringUtils.isNotEmpty(charset) ? charset : "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("decodeBase64ToString exception. s=" + s,e);
                return null;
            }
        } else {
            return null;
        }
    }


}
